package com.example.demo.controller;

import com.example.demo.model.Book;
import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping("/all")
    public List<Book> getAllBooks() {
        return bookService.getAllBooks();
    }


    @GetMapping("/{id}")
    public ResponseEntity<Book> getBookById(@PathVariable Long id) {
        return bookService.getBookById(id)
                .map(
                        book -> ResponseEntity.ok().body(book)
                ).orElse(ResponseEntity.notFound().build());
    }

    @PostMapping("/add")
    public void addBook(@RequestBody Book book) {
        System.out.println(book);
        Book book1 = bookService.addBook(book);
        System.out.println(book1);
    }

    @PostMapping("/create")
    public ResponseEntity<?> createBook(@RequestBody Book book) {
        try {
            Book book1 = bookService.AddOneBook(book);
            return ResponseEntity.ok().body(book1);

        } catch(RuntimeException e){
//            return ResponseEntity.badRequest().build(); // 400 Bad Request
            return ResponseEntity.status(500).body(e.getMessage());
        }
    }


    @PutMapping("/update/{id}")
    public ResponseEntity<Book> updateBook(@PathVariable Long id, @RequestBody Book bookDetails) {
        System.out.println(id);
        System.out.println(bookDetails);
        return ResponseEntity.ok(bookService.updateBook(id, bookDetails));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return ResponseEntity.ok().build();
    }

}
